package logic

import (
	"context"
	"errors"
	"manuscript-service/models/mysql"

	"manuscript-service/servicerpc/internal/svc"
	"manuscript-service/servicerpc/servicerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ArticleAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewArticleAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ArticleAddLogic {
	return &ArticleAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 添加
func (l *ArticleAddLogic) ArticleAdd(in *servicerpc.ArticleAddRequest) (*servicerpc.ArticleAddResponse, error) {
	// todo: add your logic here and delete this line

	var findArticle mysql.Article
	Begin := mysql.DB.Begin()
	err := findArticle.FindArticleByTitle(Begin, in.Title)
	if err == nil {
		Begin.Rollback()
		return nil, errors.New("稿件已存在")
	}
	class := &mysql.Class{
		Name: in.ClassName,
	}
	err = class.FindClassByName(Begin, in.ClassName)
	if err != nil {
		Begin.Rollback()
		return nil, err
	}
	article := &mysql.Article{
		Title:   in.Title,
		Likes:   in.Likes,
		Image:   in.Image,
		ClassId: int64(class.ID),
	}
	err = article.ArticleAdd(Begin)
	if err != nil {
		Begin.Rollback()
		return nil, err
	}
	Begin.Commit()
	return &servicerpc.ArticleAddResponse{
		ArticleId: int64(article.ID),
	}, nil
}
